﻿using AntMovement.Comm.Helper;
using AntMovement.Comm.Model;
using AntMovement.Core.LabelService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AntMovement.Comm
{
    public class Read : IChainedHandle
    {
        private Func<int, OutTimeModel> _query;
        public Func<int, OutTimeModel> Query => _query;
        private Func<int, bool, bool> _updateTime;
        public Func<int, bool, bool> UpdateTime => _updateTime;
        private ITagManager _tagManager;

        public Read(ITagManager tagManager, Func<int, OutTimeModel> query, Func<int, bool, bool> updateTime)
        {
            _tagManager = tagManager;
            _query = query;
            _updateTime = updateTime;
        }

        public void Execute(byte[] request, List<byte> respond)
        {
            respond.Add(request[2]);
            respond.Add(request[3]);
            respond.Add(request[4]);
            respond.Add(request[5]);
            int id = BytesHelper.BytesToInt(request[2], request[3], request[4], request[5]);
            OutTimeModel outTime = _query.Invoke(id);
            if (outTime != null)
            {
                string[] labels = new string[request[11]];
                try
                {
                    int labelLength = 13;
                    for (int i = 0; i < labels.Length; i++)
                    {
                        labels[i] = Encoding.ASCII.GetString(request.Skip(labelLength).Take(request[labelLength - 1]).ToArray());
                        labelLength += request[labelLength - 1];
                    }
                    Console.WriteLine(string.Join(',', labels));
                }
                catch (Exception)
                {
                    respond.AddRange(BytesHelper.ToParseTagException(request[10]));
                    return;
                }
                try
                {
                    byte[] bytes = default;
                    if (labels.Length == 1)
                    {
                        bytes = _tagManager.GetValue(labels[0]);
                    }
                    else
                    {
                        bytes = _tagManager.GetValues(labels);
                    }

                    int length = bytes.Length + 3;
                    respond.Add((byte)length);
                    respond.Add((byte)(length >> 8));
                    respond.Add(0);
                    respond.Add(0);
                    respond.Add(request[10]);
                    respond.AddRange(bytes);
                }
                catch (NotImplementedException)
                {
                    respond.AddRange(BytesHelper.ToNoLabel(request[10]));
                }
            }
            else
            {
                respond.AddRange(BytesHelper.ToUnregistered(request[10]));
            }
        }
    }
}
